import { createSlice, PayloadAction } from '@reduxjs/toolkit';

export interface Opportunity {
  id: string;
  customerName: string;
  opportunityName: string;
  value: number;
  status: 'initial' | 'communication' | 'proposal' | 'negotiation' | 'closed_won' | 'closed_lost';
  expectedCloseDate: string;
  owner: string;
  industry: string;
  description: string;
  probability: number;
  createdAt: string;
  updatedAt: string;
  contact: {
    name: string;
    phone: string;
    email: string;
    position: string;
  };
  progress: ProgressRecord[];
}

export interface ProgressRecord {
  id: string;
  date: string;
  description: string;
  type: 'call' | 'email' | 'meeting' | 'demo' | 'proposal' | 'other';
  outcome: string;
  nextAction?: string;
  createdBy: string;
}

export interface OpportunityState {
  opportunities: Opportunity[];
  currentOpportunity: Opportunity | null;
  loading: boolean;
  error: string | null;
  filters: {
    status: string[];
    industry: string[];
    valueRange: [number, number];
    dateRange: [string, string];
  };
  view: 'list' | 'kanban';
  pagination: {
    page: number;
    pageSize: number;
    total: number;
  };
}

const initialState: OpportunityState = {
  opportunities: [],
  currentOpportunity: null,
  loading: false,
  error: null,
  filters: {
    status: [],
    industry: [],
    valueRange: [0, 10000000],
    dateRange: ['', ''],
  },
  view: 'list',
  pagination: {
    page: 1,
    pageSize: 20,
    total: 0,
  },
};

const opportunitySlice = createSlice({
  name: 'opportunity',
  initialState,
  reducers: {
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload;
    },
    setError: (state, action: PayloadAction<string | null>) => {
      state.error = action.payload;
    },
    setOpportunities: (state, action: PayloadAction<Opportunity[]>) => {
      state.opportunities = action.payload;
    },
    addOpportunity: (state, action: PayloadAction<Opportunity>) => {
      state.opportunities.unshift(action.payload);
    },
    updateOpportunity: (state, action: PayloadAction<Opportunity>) => {
      const index = state.opportunities.findIndex(opp => opp.id === action.payload.id);
      if (index !== -1) {
        state.opportunities[index] = action.payload;
      }
      if (state.currentOpportunity && state.currentOpportunity.id === action.payload.id) {
        state.currentOpportunity = action.payload;
      }
    },
    deleteOpportunity: (state, action: PayloadAction<string>) => {
      state.opportunities = state.opportunities.filter(opp => opp.id !== action.payload);
      if (state.currentOpportunity && state.currentOpportunity.id === action.payload) {
        state.currentOpportunity = null;
      }
    },
    setCurrentOpportunity: (state, action: PayloadAction<Opportunity | null>) => {
      state.currentOpportunity = action.payload;
    },
    setFilters: (state, action: PayloadAction<Partial<OpportunityState['filters']>>) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    setView: (state, action: PayloadAction<'list' | 'kanban'>) => {
      state.view = action.payload;
    },
    setPagination: (state, action: PayloadAction<Partial<OpportunityState['pagination']>>) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
    addProgressRecord: (state, action: PayloadAction<{ opportunityId: string; record: ProgressRecord }>) => {
      const opportunity = state.opportunities.find(opp => opp.id === action.payload.opportunityId);
      if (opportunity) {
        opportunity.progress.push(action.payload.record);
        opportunity.updatedAt = new Date().toISOString();
      }
      if (state.currentOpportunity && state.currentOpportunity.id === action.payload.opportunityId) {
        state.currentOpportunity.progress.push(action.payload.record);
        state.currentOpportunity.updatedAt = new Date().toISOString();
      }
    },
  },
});

export const {
  setLoading,
  setError,
  setOpportunities,
  addOpportunity,
  updateOpportunity,
  deleteOpportunity,
  setCurrentOpportunity,
  setFilters,
  setView,
  setPagination,
  addProgressRecord,
} = opportunitySlice.actions;

export default opportunitySlice.reducer;
